use libc::exit;
use once_cell::sync::Lazy;
use serde::{Deserialize, Deserializer};
use crate::config::{KEYMAP, MERGED_KEYMAP};
use super::{Exec, Key} ;

#[derive(Debug, Deserialize)]
pub struct Single {
    pub on : Vec<Key> ,
    #[serde(deserialize_with="Exec::deserialize")] 
    pub exec : Vec<Exec> ,
}

#[derive(Debug)] 
pub struct Keymap {
    pub manager : Vec<Single> ,
    pub tasks :   Vec<Single> ,
    pub select : Vec<Single> ,
    pub input : Vec<Single> ,
}

impl<'de> Deserialize<'de> for Keymap {
    fn deserialize<D>(deserializer:D) -> Result<Self,D::Error> 
    where 
        D: Deserializer<'de> // 这里的反序列化比较奇怪  必须内置一个inner结构体吗？
    {
        #[derive(Deserialize)]
        struct Inner {
            keymap : Vec<Single> ,
        }
        #[derive(Deserialize)]
        struct Shadow{
            manager : Inner , 
            tasks : Inner , 
            select : Inner , 
            input : Inner , 
        }
        let shadow = Shadow::deserialize(deserializer)?;
        Ok(Self{
            manager : shadow.manager.keymap ,
            tasks : shadow.tasks.keymap ,
            select : shadow.select.keymap ,
            input : shadow.input.keymap ,
        }) 
    }
}

impl Keymap {
    pub fn new() -> Self {
        let res = toml::from_str::<Keymap>(&MERGED_KEYMAP) ;  // 第一次访问MERGED_KEYMAP完成初始化
        match res {
            Ok(keymap) => {
                // use crate::inspect; 
                // inspect!(keymap) ;
                // keymap很长 这里只截取一小段
                // Keymap { manager: [Single { on: [Key { code: Esc, shift: false, ctrl: false, alt: false }], exec: [Exec { cmd: "escape", args: [], named: {} }] },
                keymap
            },
            Err(e) => panic!("Parsing keymap failed\n{}",e) 
        }
    }
}

